﻿#include "hyjjserialgencore.h"
#include "binary2base64.h"
#include "clicenseinfo.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include "json/json.h"

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)

#elif __linux__
    #include <dlfcn.h>
#endif


#define MAX_TRIAL 365
//typedef bool Bit;
//typedef bool (*PSubKey)[16][48];
//加密解密
enum
{
    ENCRYPT	= 0,	//! 加密
    DECRYPT			//! 解密
};

//DES算法的模式
enum
{
    ECB		=	0,	//! ECB模式
    CBC				//! CBC模式
};

//Pad填充的模式
enum
{
    PAD_ISO_1 =	0,	//! ISO_1填充：数据长度不足8比特的倍数，以0x00补足，如果为8比特的倍数，补8个0x00
    PAD_ISO_2,		//! ISO_2填充：数据长度不足8比特的倍数，以0x80,0x00..补足，如果为8比特的倍数，补0x80,0x00..0x00
    PAD_PKCS_7		//! PKCS7填充：数据长度除8余数为n,以(8-n)补足为8的倍数
};

std::string HyjjSerialGenCore::DesDecodeFromString(std::string strValue, unsigned char *key)
{
    unsigned char input[8];
    unsigned char output[8];
    unsigned char outstr[1024];  //最大1024

    //base64转二进制
    int iBase64Size = 0;
    unsigned char * buffer = binary2Base64::fromBase64(strValue,binary2Base64::eBase64Encoding,iBase64Size);
//	strtobit(buffer, iBase64Size);
    //初始化
    for(int i=0; i<1024; i++)
        outstr[i]=0;

    int n=0;
    if(buffer)
    {
        while(n < iBase64Size)
        {
            memset((void *)input,0,8);
            memcpy(input,buffer+n,(iBase64Size - n>=8)?8:iBase64Size - n);
            RunDesDecode(input, output, key);
            for(int i=0; i<8; i++)
            {
                outstr[n+i]=output[i];
            }
            n+=8;
        }
    }
    else
    {
        return "";
    }
    std::string strResult(outstr,outstr + iBase64Size);
    free(buffer);
    return strResult;
}

std::string HyjjSerialGenCore::DesEncodeFromString(std::string strValue,
                                                   std::string strSavePath,
                                                   unsigned char *key)
{
    unsigned char input[8];
    unsigned char output[8];
    int iSize = strValue.size();

	int n_i = iSize % 8;
	if (n_i > 0) n_i = 8;
	int iLen = (iSize / 8) * 8 + n_i;

    unsigned char* tmp = (unsigned char*)malloc(iLen);
    int n=0;
    if(iSize > 0)
    {
        while(n < iLen)
        {
            memset((void *)input,0,8);
            strValue.copy((char*)input, (iSize - n > 8) ? 8 : (iSize - n),n);
            RunDesEncode(input, output, key);
            memcpy(tmp+n,output, 8);
            n+=8;
        }
    }

    if(!strSavePath.empty())
    {
        std::ofstream f(strSavePath+"/license.dat",std::ios::binary);
        if(f)
        {
            f.write((char*)tmp, n);      //fwrite以char *的方式进行写出，做一个转化
            f.close();
        }
    }
//    strtobit(tmp, n);
    std::string strRet = binary2Base64::toBase64(tmp, n,binary2Base64::eBase64Encoding);
	free(tmp);
    return strRet;
}
